﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Share.Models;

namespace Share.Services
{
    class DS
    {
        public enum OPTION { RECURSIVE }

        private DB db;
        private Directory current;
        private string ns;

        public DS(DB db, string ns)
        {
            this.db = db;
            this.ns = ns;
            current = db.Directories.FirstOrDefault(d => d.Path == "/" && d.Name == ns);
            if (current == null)
            {
                Directory d = new Directory();
                d.Name = ns;
                db.Directories.Add(d);
                db.SaveChanges();
                current = d;
            }
        }

        public string cd()
        {
            return current.Path + current.Name + "/";
        }

        public void cd(Directory d)
        {
            current = d;
        }

        public void cd(string p)
        {
            string path,name;
            if (p.StartsWith("/"))
            {
                if (p.LastIndexOf('/') == 0)
                {
                    path = "/";
                    name = ns;
                }
                else
                {
                    path = "/" + ns + p.Substring(0, p.LastIndexOf('/') + 1);
                    name = p.Substring(p.LastIndexOf('/') + 1);
                }
            }
            else
            {
                path = cd();
                name = p;
            }

            current = db.Directories.First<Directory>(d => d.Path == path && d.Name == name);
        }

        public void mkdir(string name)
        {
            Directory d = new Directory();
            d.Name = name;
            d.Level = current.Level + 1;
            d.Parent = current;
            d.Path = cd();

            db.Directories.Add(d);
            db.SaveChanges();
        }

        public void rmdir(string name, int option)
        {
            string p = cd();
            Directory dir = db.Directories.First<Directory>(d => d.Path == p && d.Name == name);
            if (dir != null)
            {
                db.Directories.Remove(dir);
                db.SaveChanges();
            }
        }

        public void rename(string newName)
        {
            current.Name = newName;
            db.SaveChanges();
        }

        public void rename(string dir, string newName)
        {
            string p = cd();
            Directory d = db.Directories.First(c => c.Path == p && c.Name == dir);
            d.Name = newName;
            db.SaveChanges();
        }

        public IEnumerable<Directory> list()
        {
            //return db.Directories.Where(d => d.Path == cd()).AsEnumerable();
            return current.Subs;
        }
    }
}
